package com.huilian.iotbox.client.service.impl;

import com.huilian.iotbox.client.dao.AgencyDao;
import com.huilian.iotbox.client.service.AgencyService;
import com.huilian.iotbox.client.service.DeviceService;
import com.huilian.iotbox.data.dto.AgencyDto;
import com.huilian.iotbox.data.enums.ChannelTypeEnum;
import com.huilian.iotbox.data.po.Agency;
import com.huilian.iotbox.data.vo.DeviceVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;

/**
 * @author lizhiquan
 * @CreateDate: 2021-03-30-20-57
 * @Description:
 */
@Slf4j
@Service
public class AgencyServiceImpl implements AgencyService {
    @Resource
    private AgencyDao agencyDao;
    @Autowired
    private DeviceService deviceService;

    /**
     * 根据机构id获取机构信息
     */
    @Override
    public Agency getAgencyById(Integer id) {
        return agencyDao.findOneAgencyById(id);
    }

    @Override
    public AgencyDto getAgencyByIdAndChannelType(Integer agencyId, String channelType) {
        AgencyDto agencyDto = agencyDao.getAgencyDtoById(agencyId);
        //获取机构对应支付宝微信费率
        BigDecimal baseFeeValue = BigDecimal.ZERO;
        if (ChannelTypeEnum.Ali.getCode().equals(channelType)) {
            baseFeeValue = agencyDto.getAliFee();
        } else if (ChannelTypeEnum.WX.getCode().equals(channelType)) {
            baseFeeValue = agencyDto.getWxFee();
        }
        agencyDto.setFee(baseFeeValue);
        return agencyDto;
    }

    @Override
    public AgencyDto getDeviceAgencyByDeviceNoAndChannelType(String deviceNo, Integer merchantStoreId, String channelType) {
        AgencyDto agencyDto = null;
        if (StringUtils.isEmpty(deviceNo)) {
            List<DeviceVo> deviceVoList = deviceService.findDeviceByMerchantStoreId(merchantStoreId);
            if (StringUtils.isEmpty(deviceVoList) || deviceVoList.size() == 0) {
                Agency agency = agencyDao.findOneAgencyById(1);
                agencyDto = new AgencyDto();
                BeanUtils.copyProperties(agency, agencyDto);
            } else {
                log.info("deviceNo:{} ", deviceVoList.get(0).getDeviceNo());
                agencyDto = agencyDao.getDeviceAgencyByDeviceNoAndChannelType(deviceVoList.get(0).getDeviceNo());
            }
        } else {
            agencyDto = agencyDao.getDeviceAgencyByDeviceNoAndChannelType(deviceNo);
        }

        //获取机构对应支付宝微信费率
        BigDecimal baseFeeValue = BigDecimal.ZERO;
        if (ChannelTypeEnum.Ali.getCode().equals(channelType)) {
            baseFeeValue = agencyDto.getAliFee();
        } else if (ChannelTypeEnum.WX.getCode().equals(channelType)) {
            baseFeeValue = agencyDto.getWxFee();
        }
        agencyDto.setFee(baseFeeValue);
        return agencyDto;
    }
}
